package com.sfpay.coreplatform.member.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sfpay.coreplatform.account.valueobject.dto.ResetAccountPsw;
import com.sfpay.coreplatform.account.valueobject.dto.UpdateAccountPsw;
import com.sfpay.coreplatform.account.valueobject.tmo.AccountVO;
import com.sfpay.coreplatform.member.common.MemberResponseCode;
import com.sfpay.coreplatform.member.common.util.EncryptUtil;
import com.sfpay.coreplatform.member.persistence.dao.IAccountRelationDao;
import com.sfpay.coreplatform.member.service.IAccountService;
import com.sfpay.coreplatform.member.service.exception.MemberServiceException;
import com.sfpay.coreplatform.member.service.proxy.account.IAccProxyQueryService;
import com.sfpay.coreplatform.member.service.proxy.account.IAcctProxyManageService;
import com.sfpay.coreplatform.member.service.validate.ValidateUtil;
import com.sfpay.coreplatform.member.valueobject.dto.MemberAccount;

@Service
public class AccountServiceImpl implements IAccountService {

	@Resource
	private IAcctProxyManageService acctProxyManageService;
	@Resource
	private IAccountRelationDao accountRelationDao;
	@Resource
	private IAccProxyQueryService accProxyQueryService;
	
	private static Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);
	
	@Override
	public MemberAccount queryAccountByNo(Long accountNo) throws MemberServiceException 
	{
		if (logger.isDebugEnabled()) 
		{
			logger.debug("queryAccountByNo begin:" + accountNo);
		}
		ValidateUtil.checkObjectParamIsNull(accountNo, "accountNo");
		MemberAccount memberAccount;
		try 
		{
			//查询会员关联账号
			memberAccount = accountRelationDao.queryAccountInfoByNo(accountNo);
		} 
		catch (Exception e) 
		{
			logger.error("method queryAccount query member ref acc exception", e);
			if (SQLException.class.isInstance(e)) 
			{
				throw new MemberServiceException(MemberResponseCode.MEMBER_DB_EXCEPTION, ""
								+ ((SQLException) e).getErrorCode(), e);
			} 
			else 
			{
				throw new MemberServiceException(MemberResponseCode.MEMBER_DB_EXCEPTION, 
						"method queryAccountByNo save excption",e);
			}
		}
		if(memberAccount != null)
		{
			AccountVO accountVO = accProxyQueryService.findAccountInfoByAccountNo(accountNo);
			if(accountVO != null)
			{
				memberAccount.setCashAmount(accountVO.getCashAmount());
				memberAccount.setAccountDetailState(accountVO.getAccountState().toString());
				memberAccount.setOverdraftAmountLimit(accountVO.getOverdraftAmountLimit());
				memberAccount.setUnAvailableAmount(accountVO.getFreezeAmount());
			}
		}
		if (logger.isDebugEnabled()) 
		{
			logger.debug("queryAccountByNo end:" + accountNo);
		}
		return memberAccount;
	}
	
	
	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public List<MemberAccount> queryAccount(Long memberNo, String productType) throws MemberServiceException 
	{
		ValidateUtil.checkObjectParamIsNull(memberNo, "memberNo");
		ValidateUtil.checkParamIsNull(productType, "productType");

		List<MemberAccount> accountList = null;
		try 
		{
			//查询会员关联账号
			accountList = accountRelationDao.queryAccountInfo(memberNo,
					productType);
		} 
		catch (Exception e) 
		{
			logger.error("method queryAccount query member ref acc exception", e);
			if (SQLException.class.isInstance(e)) 
			{
				throw new MemberServiceException(MemberResponseCode.MEMBER_DB_EXCEPTION, ""
								+ ((SQLException) e).getErrorCode(), e);
			} 
			else 
			{
				throw new MemberServiceException(MemberResponseCode.MEMBER_DB_EXCEPTION, 
						"method queryAccount save excption",e);
			}
		}
		if (accountList != null && accountList.size() > 0) 
		{
			List<Long> accounts = new ArrayList<Long>();
			for (MemberAccount memberAccount : accountList) 
			{
				accounts.add(memberAccount.getAccountNo());
			}
			if (accounts.size() > 0) 
			{
				try 
				{
					//查询账号信息
					Map<Long, AccountVO> accMap = accProxyQueryService.findAccountInfo(accounts);
					for (MemberAccount memberAccount : accountList) 
					{
						AccountVO accountVO = accMap.get(memberAccount.getAccountNo());
						if(accountVO != null)
						{
							memberAccount.setCashAmount(accountVO.getCashAmount());
							memberAccount.setAccountDetailState(accountVO.getAccountState().toString());
							memberAccount.setOverdraftAmountLimit(accountVO.getOverdraftAmountLimit());
							memberAccount.setUnAvailableAmount(accountVO.getFreezeAmount());
						}
					}
					accMap=null;
				}
				catch (MemberServiceException e) 
				{
					logger.error("method queryAccount query acc exception", e);
					throw e;
				}
			}
		}

		return accountList;
	}

	/**
	 * 更新账户密码 *
	 * 
	 * @param accountNo
	 *            账户号码
	 * @param oldPwd
	 *            旧密码
	 * @param newPwd
	 *            新密码
	 * @throws MemberServiceException
	 */
	@Override
	@Transactional(rollbackFor= MemberServiceException.class,propagation=Propagation.REQUIRED)
	public void updateAccountPwd(Long accountNo, String oldPwd, String newPwd)
			throws MemberServiceException 
	{
		if (logger.isDebugEnabled()) 
		{
			logger.debug("updateAccountPwd begin:" + accountNo);
		}

		ValidateUtil.checkObjectParamIsNull(accountNo, "accountNo");
		ValidateUtil.checkParamIsNull(oldPwd, "oldPwd");
		ValidateUtil.checkParamIsNull(newPwd, "newPwd");
		UpdateAccountPsw updateAccountPsw = new UpdateAccountPsw();
		updateAccountPsw.setAccountNo(accountNo);
		updateAccountPsw.setAccountPasswdOld(EncryptUtil.encryptPwd(oldPwd));
		updateAccountPsw.setAccountPasswdNew(EncryptUtil.encryptPwd(newPwd));
		acctProxyManageService.updateAccountPsw(updateAccountPsw);

		if (logger.isDebugEnabled()) 
		{
			logger.debug("updateAccountPwd end:" + accountNo);
		}

	}

	/**
	 * 重置账户密码 *
	 * 
	 * @param accountNo
	 * @param newPwd
	 * @throws MemberServiceException
	 */
	@Override
	@Transactional(rollbackFor= MemberServiceException.class,propagation=Propagation.REQUIRED)
	public void resetAccountPwd(Long accountNo, String newPwd)
			throws MemberServiceException 
	{
		if (logger.isDebugEnabled()) 
		{
			logger.debug("resetAccountPwd begin:" + accountNo);
		}
		ValidateUtil.checkObjectParamIsNull(accountNo, "accountNo");
		ValidateUtil.checkParamIsNull(newPwd, "newPwd");
		ResetAccountPsw resetAccountPsw = new ResetAccountPsw();
		resetAccountPsw.setAccountNo(accountNo);
		resetAccountPsw.setAccountPasswdNew(EncryptUtil.encryptPwd(newPwd));
		acctProxyManageService.resetAccountPsw(resetAccountPsw);
		if (logger.isDebugEnabled()) 
		{
			logger.debug("resetAccountPwd end:" + accountNo);
		}
	}
	
	/**
	 * 禁止贷方交易
	 */
	@Override
	public void forbidAccountCredit(Long accountNo) throws MemberServiceException 
	{
		if (logger.isDebugEnabled()) 
		{
			logger.debug("forbidAccountCredit begin:" + accountNo);
		}
		ValidateUtil.checkObjectParamIsNull(accountNo, "accountNo");
		acctProxyManageService.makeAccountForbidIn(accountNo);
		if (logger.isDebugEnabled()) 
		{
			logger.debug("forbidAccountCredit end:" + accountNo);
		}
		
	}
	
	/**
	 * 禁止借方交易
	 */
	@Override
	public void forbidAccountDeposit(Long accountNo) throws MemberServiceException 
	{
		if (logger.isDebugEnabled()) 
		{
			logger.debug("forbidAccountDeposit begin:" + accountNo);
		}
		ValidateUtil.checkObjectParamIsNull(accountNo, "accountNo");
		acctProxyManageService.makeAccountForbidOut(accountNo);
		if (logger.isDebugEnabled()) 
		{
			logger.debug("forbidAccountDeposit end:" + accountNo);
		}
	}

	@Override
	public void makeAccountNormal(Long accountNo) throws MemberServiceException 
	{
		if (logger.isDebugEnabled()) 
		{
			logger.debug("makeAccountNormal begin:" + accountNo);
		}
		ValidateUtil.checkObjectParamIsNull(accountNo, "accountNo");
		acctProxyManageService.makeAccountNormal(accountNo);
		if (logger.isDebugEnabled()) 
		{
			logger.debug("makeAccountNormal end:" + accountNo);
		}
	}

	@Override
	public void makeAccountCancel(Long accountNo) throws MemberServiceException 
	{
		if (logger.isDebugEnabled()) 
		{
			logger.debug("makeAccountCancel begin:" + accountNo);
		}
		ValidateUtil.checkObjectParamIsNull(accountNo, "accountNo");
		acctProxyManageService.makeAccountCancel(accountNo);
		if (logger.isDebugEnabled()) 
		{
			logger.debug("makeAccountCancel end:" + accountNo);
		}
		
	}


	@Override
	public void makeAccountActive(Long accountNo) throws MemberServiceException
	{
		if (logger.isDebugEnabled())
		{
			logger.debug("makeAccountActive begin:" + accountNo);
		}
		ValidateUtil.checkObjectParamIsNull(accountNo, "accountNo");
		acctProxyManageService.makeAccountActive(accountNo);
		if (logger.isDebugEnabled()) 
		{
			logger.debug("makeAccountActive end:" + accountNo);
		}
	}
}
